﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UAParser;

namespace Template.Infrastructure.Net
{
    public class WebClientInfoProvider : IWebClientInfoProvider
    {


        private readonly IHttpContextAccessor _httpContextAccessor = null;
        private readonly UserAgent _userAgent = null;
        private readonly string _userAgentStr = null;
        public WebClientInfoProvider(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _httpContext = httpContextAccessor?.HttpContext;
            _userAgentStr = _httpContext?.Request.Headers[HeaderNames.UserAgent].FirstOrDefault();
            _userAgent = new UserAgent(_userAgentStr ?? string.Empty);
        }

        private HttpContext _httpContext = null;

        public string BrowserInfo => GetBrowserInfo();


        public string System => GetSystemName();
        public string ClientIpAddress => GetClientIpAddress();

        public string UserAgent => GetUserAgent();

        public string RequestUrl => GetUrl();


        private string GetUserAgent()
        {
            return _userAgent.GetUserAgent() ?? string.Empty;
        }



        /// <summary>
        /// 得到计算机名
        /// </summary>
        /// <returns></returns>
        private string GetSystemName()
        {
            return _userAgent.GetSystem();
        }

        /// <summary>
        /// 得到浏览器信息
        /// </summary>
        /// <returns></returns>
        private string GetBrowserInfo()
        {

            return _userAgent.GetBrowser();
        }




        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        private string GetClientIpAddress()
        {

            string ip = _httpContext?.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip)&& _httpContext != null)
            {
                ip = _httpContext.Connection.RemoteIpAddress.ToString();
            }
            return ip ?? string.Empty;
        }

        private string GetUrl()
        {

           return _httpContext?.Request.GetEncodedPathAndQuery() ?? string.Empty;
          
        }
    }
}
